package com.huluobo.a2112mvvmdouyindemo.demoMVVM;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import com.huluobo.a2112mvvmdouyindemo.R;
import com.huluobo.a2112mvvmdouyindemo.databinding.ActivityLoginMvvmDemoBinding;
import com.huluobo.a2112mvvmdouyindemo.demoMVP.UserDemoBean;

public class LoginMVVMDemoActivity extends AppCompatActivity {

    //当在Gradle打开DataBinding和ViewBinding的开关后,每个xml文件都会对应的生成一个类,命名方式是xml的名字后面加上binding
    //同时,所有xml控件的获取,都可以通过binding拿到
    //通过DataBindingUtils来重新给activity赋值布局
    ActivityLoginMvvmDemoBinding activityLoginMvvmDemoBinding;
    LoginDemoViewModel loginDemoViewModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activityLoginMvvmDemoBinding = DataBindingUtil.setContentView(this, R.layout.activity_login_mvvm_demo);
        //ViewModel不能直接new,需要公国ViewModelProvider来拿到对应的class,通过反射的机制
        loginDemoViewModel = new ViewModelProvider(this).get(LoginDemoViewModel.class);

        activityLoginMvvmDemoBinding.loginDemoBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loginDemoViewModel.login(
                        activityLoginMvvmDemoBinding.loginDemoUsername.getText().toString(),
                        activityLoginMvvmDemoBinding.loginDemoPassword.getText().toString()
                );
            }
        });

        //观察viewModel中成功的LiveData是否改变
        loginDemoViewModel.success.observe(this, new Observer<UserDemoBean>() {
            @Override
            public void onChanged(UserDemoBean userDemoBean) {
                Toast.makeText(LoginMVVMDemoActivity.this, "登录成功:" + userDemoBean.getUsername(), Toast.LENGTH_SHORT).show();
            }
        });

        //观察ViewModel中失败的LiveData是否改变
        loginDemoViewModel.failed.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                Toast.makeText(LoginMVVMDemoActivity.this, "登录失败:" + s, Toast.LENGTH_SHORT).show();
            }
        });

    }
}